import React from "react";
import "./App.css";

function Square(props) {
  return (
    <button
      className="square"
      onClick={props.onClick}
      style={{ background: props.hightLight ? "yellowgreen" : "#fff" }}
    >
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    console.log(this.props.squares);
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
        hightLight={this.props.winSquares.indexOf(i) !== -1}
        key={i}
      />
    );
  }

  renderRow(line) {
    return [0, 1, 2].map((i) => {
      return this.renderSquare(line * 3 + i);
    });
  }

  renderMatrix() {
    return [0, 1, 2].map((i) => {
      return (
        <div className="board-row" key={i}>
          {this.renderRow(i)}
        </div>
      );
    });
  }

  render() {
    return <div>{this.renderMatrix()}</div>;
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null),
          position: null,
          token: null,
          selected: true,
          index: 0,
        },
      ],
      stepNumber: 0,
      xIsNext: true,
      reversedHistory: false,
    };
  }

  handleClick(i) {
    const history = this.state.history
      .slice(0, this.state.stepNumber + 1)
      .map((item) => {
        item.selected = false;
        return item;
      });
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    const position = `( ${Math.floor(i / 3) + 1}, ${(i % 3) + 1} )`;

    this.setState({
      history: history.concat([
        {
          squares,
          position,
          token: squares[i],
          index: history.length,
          selected: true,
        },
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: step % 2 === 0,
    });
  }

  handleClickHistory(move) {
    const history = this.state.history.slice();

    for (let i = 0; i < history.length; i++) {
      const item = history[i];
      item.selected = i === move;
    }

    this.setState({
      history,
    });

    this.jumpTo(move);
  }

  reverseHistory() {
    this.setState({
      reversedHistory: !this.state.reversedHistory,
    });
  }

  render() {
    let history = this.state.history;
    if (this.state.reversedHistory) {
      history = history.reverse();
    }
    const current = history.find(
      (item) => item.index === this.state.stepNumber
    );
    const winInfo = calculateWinner(current.squares);
    let winner = null;
    let winSquares = [];
    if (winInfo) {
      winner = winInfo[0];
      winSquares = winInfo.slice(1);
    }

    const moves = history.map((step) => {
      const move = step.index;
      const desc = move ? "Go to move #" + move : "Go to game start";
      const content = move
        ? `${desc} - ${step.token} - ${step.position}`
        : desc;
      return (
        <li key={move}>
          <button
            style={{
              fontWeight: step.selected ? "bold" : "normal",
            }}
            onClick={() => this.handleClickHistory(move)}
          >
            {content}
          </button>
        </li>
      );
    });

    let status;
    if (winner) {
      status = "Winner: " + winner;
    } else {
      if (this.state.stepNumber === 9) {
        status = "Draw";
      } else {
        status = "Next player: " + (this.state.xIsNext ? "X" : "O");
      }
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            winSquares={winSquares}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <div>
            <button onClick={() => this.reverseHistory()}>
              reverse history
            </button>
            <ol>{moves}</ol>
          </div>
        </div>
      </div>
    );
  }
}

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return [squares[a], a, b, c];
    }
  }
  return null;
}

function App() {
  return (
    <div className="App">
      <Game />
    </div>
  );
}

export default App;
